package question.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import question.pojo.Answer;
import question.pojo.Question;
import question.service.DBUtils;

public class QuestionDao {
	
	//������Ŀ
	public void insertQuestion(String queid,String que) throws Exception{
		
		//���ݿ�����
		Connection con = DBUtils.getCon();
		
		//ִ��sql���
		String sql="insert into question values(?,?)";
		PreparedStatement pre=con.prepareStatement(sql);
		pre.setString(1, queid);
		pre.setString(2, que);
		pre.execute();
		con.close();
	}
	
	//�������ɾ������
	public List<Question> deleteQueById(String queid) throws Exception {
		
		//���ݿ�����
		Connection con = DBUtils.getCon();
		
		//ִ��sql���
		String sql="delete from question where queid=?";
		PreparedStatement pre=con.prepareStatement(sql);
		pre.setString(1,queid);
		pre.execute();
		con.close();
		
		//�ٲ�ѯ��Ŀ
		QuestionDao qd = new QuestionDao();
		List<Question> qlist = qd.selectAllQues();
		return qlist;
	}
	
	//ɾ����������
	public void deleteAllQues() throws Exception {
		
		//���ݿ�����
		Connection con = DBUtils.getCon();
		
		//ִ��sql���
		String sql="delete question";
		PreparedStatement pre=con.prepareStatement(sql);
		pre.execute();
		con.close();
	}
	
	//�޸�����
	public void updateQuestion(String queid,String que) throws Exception {
		
		//���ݿ�����
		Connection con = DBUtils.getCon();
		
		//ִ��sql���
		String sql="update question set que=? where queid=?";
		java.sql.PreparedStatement pre=con.prepareStatement(sql);
		pre.setString(1,que);
		pre.setString(2,queid);
		pre.execute();
		con.close();
	}
	
	//������Ų�ѯ����
	public Question selectQueById(String queid) throws Exception {
		
		//���ݿ�����
		Connection con = DBUtils.getCon();
		
		// ִ��sql���
		String sql = "select * from question where queid=?";
		PreparedStatement pre = con.prepareStatement(sql);
		pre.setString(1, queid);
		ResultSet res = pre.executeQuery();
		Question question=null;
		while (res.next()) {
			String que = res.getString(2);
			AnswerDao ad = new AnswerDao();
			List<Answer> alist = ad.selectAnswers(queid);
			question = new Question(queid, que,alist);
		}
		con.close();
		return question;
	}
	
	//��ѯ����������
	public List<Question> selectAllQues() throws Exception {
		
		//���ݿ�����
		Connection con = DBUtils.getCon();
		
		// ִ��sql���
		String sql = "select * from question";
		PreparedStatement pre = con.prepareStatement(sql);
		ResultSet res = pre.executeQuery();
		List<Question> qlist = new ArrayList<Question>();
		AnswerDao ad = new AnswerDao();
		while (res.next()) {
			String queid = res.getString(1);
			String que = res.getString(2);
			List<Answer> alist = ad.selectAnswers(queid);
			Question ques = new Question(queid, que,alist);
			qlist.add(ques);
		}
		con.close();
		return qlist;
	}
}
